<template>
  <div class="LoginForm">
    <el-row :gutter="10" class="loginMode" justify="end">
      <el-col :span="7" style="text-align:right;" @click="isMsgLogin = false" v-if="isMsgLogin">使用账号登录</el-col>
      <el-col :span="7" style="text-align:right;" @click="isMsgLogin = true" v-else>使用短信登录</el-col>
    </el-row>
    <el-form ref="formRef" :model="form" style="margin-top:20px;" :rules="rules">
       <template v-if="isMsgLogin">
        <el-form-item prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" :prefix-icon="Phone"></el-input>
        </el-form-item>
        <el-form-item prop="code">
          <el-input v-model="form.code" placeholder="请输入验证码" :prefix-icon="Lock">
            <template #suffix>
              <div class="code" @click.stop="sendCode">
                {{time === 0 ? '发送验证码' : `${time}秒后重试`}}
              </div>
            </template>
          </el-input>
        </el-form-item>
      </template>
      <template v-else>
        <el-form-item prop="account">
        <el-input v-model="form.account" placeholder="请输入用户名" :prefix-icon="User"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input type="password" v-model="form.password" placeholder="请输入密码" :prefix-icon="Lock"></el-input>
        </el-form-item>
      </template>
     
      <el-form-item class="isAgree" prop="isAgree">
        <el-checkbox v-model="form.isAgree">我已同意</el-checkbox>
        <a  href="javascript:;">《隐私条款》</a> 和
        <a  href="javascript:;">《服务条款》</a>
      </el-form-item>
      <el-form-item>
        <el-button color="#27BA9B" size="large" style="width:100%; margin:auto; color:white;" @click="submit">登录</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10">
      <el-col :span="12" >登录</el-col>
      <el-col :span="12" style="text-align:right">
        <el-row :gutter="0">
          <el-col :span="12">忘记密码</el-col>
          <el-col :span="12">免费注册</el-col>
        </el-row>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { reactive, ref } from 'vue';
import { User, Lock, Phone } from '@element-plus/icons-vue'
import { userAccountLogin, userMobileLogin, userMobileLoginMsg } from '@/api/user';
import { validatorAccount, validatorPassword, validatorPhone, validatorCode, validatorIsAgree } from '@/utils/validator'
import { ElMessage } from 'element-plus'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
import { useIntervalFn } from '@vueuse/core'
export default {
  name: 'LoginForm',
  setup() {
    // 是否短信登录
    const isMsgLogin = ref(false)
    const form = reactive({
      account: 'zhousg',
      password: 123456,
      phone: 13666666666,
      code: null,
      isAgree: true
    })
    // 表单验证
    const rules = reactive({
      account: [{ validator: validatorAccount, trigger:'blur'}],
      password: [{ validator: validatorPassword, trigger:'blur'}],
      phone: [{ validator: validatorPhone, trigger:'blur'}],
      code: [{ validator: validatorCode, trigger:'blur'}],
      isAgree: [{ validator: validatorIsAgree, trigger:'change'}]
    })
    const formRef = ref(null)
    const store = useStore()
    const router = useRouter()
    const route = useRoute()
    // 发送验证码
    const time = ref(0)
    let timer = null
    // pause 暂停， resume 开始 
    const { pause, resume } = useIntervalFn(() => {
      time.value--
      if(time.value <= 0){
        pause()
      }
    }, 1000, { immediate: false })
    const sendCode = async ()=>{
      formRef.value.validateField('phone',async (value)=>{
        if(value){
            if(time.value === 0){
              await userMobileLoginMsg({mobile:form.phone})
              form.code = 123456
              time.value = 10
              resume()
            }
        }
      })
    }
    const submit = () => {
      formRef.value.validate( async (valid)=>{
        if(valid){
          // 短信登录
          let res = {}
          if(isMsgLogin.value) {
              res = await userMobileLogin({mobile: form.phone, code: form.code})
              
          }else{
            // 账号登录 
              res = await userAccountLogin({account: form.account, password: form.password})
          }
          const { id, account, nickname, avatar, token, mobile } = res.result
          store.commit('user/setUser',{ id, account, nickname, avatar, token, mobile })
           // 合并购物车操作
          store.dispatch('cart/mergeCart').then(() => {
            // 2. 提示
            ElMessage.success('登录成功')
            // 3. 跳转
            router.push(route.query.redirectUrl || '/')
          })
        }else{
          return false
        }
      })
    }
    return {
      form,
      User,
      Lock,
      Phone,
      rules,
      isMsgLogin,
      submit,
      formRef,
      sendCode,
      time
    }
  }
}
</script>

<style lang="scss" scoped>
.LoginForm {
  padding: 20px;
  .isAgree{
    a{
      color: #4f4ae0 ;
    }
  }
  .code{
    width: 100px;
    background: #eee;
    height: 48px;
    line-height: 48px;
    margin-right: -10px;
    margin-top: 1px;
    cursor: pointer;
  }
}
::v-deep .el-input__inner{
  height: 50px;
  &:focus{
    box-shadow:none;
    border: 1px solid #27BA9B;
  }
}
</style>